package com.tdcy.sys.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tdcy.framework.BaseController;
import com.tdcy.framework.exception.BaseException;
import com.tdcy.framework.util.StringUtils;
import com.tdcy.framework.util.SysUtils;
import com.tdcy.sys.util.ExpImpUtils;
import com.tdcy.sys.util.SessionUtilExt;
import com.tdcy.sys.util.excel.ExcelUtils;

/**
 * @Description 数据库备份还原
 */
@Controller
@RequestMapping(value = "/expimp")
public class ExpImpControllber extends BaseController {
	/**
	 * 导入数据
	 * 
	 * @return
	 */
	public Object imp() {
		// // 保存文件
		// String uploadDir = SysUtils.getWebRoot() +
		// AppParamsHelper.getAppParam("upload_folder", "/upload");
		// FileItem excel = this.getFileItem("imp_employee");
		// if (excel == null) {
		// throw new BaseException("导入文件无效！请重新上传");
		// }
		// UploadFile file = FileUploader.uploadFile(excel, uploadDir);
		//
		// // 读取数据
		// LoadExl exl = new LoadExl();
		// String templatePath = SysHelper.getWebInfPath() +
		// "excel/employee.xls";
		// exl.setTempleteFile(templatePath);
		// exl.setDataFile(file.getFilePath());
		// List<Map<String, Object>> data = exl.readData();
		// if (data == null) {
		// throw new BaseException("导入数据和模板不符合,请使用导出模板填充数据！");
		// }
		//
		// // 入库
		// employsvc.importEmploy(data);
		// this.saveIframeReturn("导入成功", null);
		return null;
	}

	/**
	 * 导出数据到 excel
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exp")
	public Object exp(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String xlsName = SessionUtilExt.getSessionValue(request, ExpImpUtils.TEMPLATE_NAME, "");
		if (StringUtils.isEmpty(xlsName)) {
			throw new BaseException("模板名称不能为空");
		}
		String xmlFilePath = SysUtils.getResource(request.getSession().getServletContext(), "resource" + File.separator + "template" + File.separator) + xlsName;
		File xmlFile = new File(xmlFilePath);
		if (!xmlFile.exists()) {
			throw new BaseException("模板不存在");
		}

		Object obj1 = SessionUtilExt.getSesion(request.getSession(), ExpImpUtils.TEMPLATE_LIST_DATA);
		if (obj1 == null) {
			throw new BaseException("模板数据不能为空");
		}

		List<Object> uobjlist = (List<Object>) obj1;
		if (uobjlist.size() > 65536) {
			throw new BaseException("超过excel的最大导出行数(65535),请添加过滤条件然后再进行导出");
		}

		Object obj2 = SessionUtilExt.getSesion(request.getSession(), ExpImpUtils.TEMPLATE_MAP_DATA);
		Map<String, String> map = null;
		if (obj2 != null) {
			map = (Map<String, String>) obj2;
		}
		Class clazz = (Class) SessionUtilExt.getSesion(request.getSession(), ExpImpUtils.TEMPLATE_CLASS);

		// 导出文件
		String outputFileName = (String) SessionUtilExt.getSesion(request.getSession(), ExpImpUtils.EXPORTFILE_NAME);
		String outFilePath = SysUtils.getResource(request.getSession().getServletContext(), "temp") + System.currentTimeMillis();
		ExcelUtils.getInstance().exportObjects2Excel(xmlFilePath, 0, uobjlist, map, clazz, false, outFilePath);

		this.doExport(response, outputFileName, outFilePath);
		return null;
	}

	public void doExport(HttpServletResponse response, String outFileName, String filePath) {
		Long currTimeStart = System.currentTimeMillis();
		System.out.println("开始导出excel");

		FileInputStream fis = null;
		BufferedOutputStream bufferedOutPut = null;
		File f = new File(filePath);
		try {
			String fileName = new String(outFileName.getBytes("GBK"), "iso8859-1");
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);// 指定下载的文件名
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = null;
			output = response.getOutputStream();

			fis = new FileInputStream(f);
			byte[] bs = new byte[fis.available()];
			fis.read(bs);
			bufferedOutPut = new BufferedOutputStream(output);
			bufferedOutPut.flush();
			bufferedOutPut.write(bs);
			Long currTimeEnd = System.currentTimeMillis();
			System.out.println("导出excel结束,用时：" + (currTimeEnd - currTimeStart));
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Output   is   closed ");
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (bufferedOutPut != null) {
					bufferedOutPut.close();
				}
				if (f.exists()) {
					FileUtils.deleteQuietly(f);
				}
			} catch (Exception e) {

			}
		}
	}
}
